package com.yang.servlet;

import com.yang.pojo.Brand;
import com.yang.service.GoodService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/GoodAddServlet")
public class GoodAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        GoodService goodService = new GoodService();
        String goodName = request.getParameter("goodName");
        String goodPath = request.getParameter("goodPath");
        int goodMinPrice = Integer.parseInt(request.getParameter("goodMinPrice"));
        int goodFifthPrice = Integer.parseInt(request.getParameter("goodFifthPrice"));
        int brandId = Integer.parseInt(request.getParameter("brandId"));
        try {
            int goodId = goodService.saveGood(goodName, goodPath, goodMinPrice, goodFifthPrice, brandId);
            String[] infoDetailIds = request.getParameterValues("infoDetailId");
            for (int i = 0; i < infoDetailIds.length; i++) {
                int infoDetailId = Integer.parseInt(infoDetailIds[i]);
                int price = Integer.parseInt(request.getParameter("price_" + infoDetailId));
                boolean b = goodService.saveGoodAndInfoDetail(goodId, infoDetailId, price);
            }
            String tips = goodId > 0?"<label style='color:green'>添加成功</label>":"<label style='color:red'>添加失败</label>";
            request.setAttribute("tips",tips);
            request.getRequestDispatcher("prompt.jsp").forward(request,response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }







    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
